import Flutter
import UIKit
import Foundation

@_exported import KCTBluetoothSDK
@_exported import KCTHTTPSessionSDK

@_exported import YYModel
@_exported import SSZipArchive
@_exported import SVProgressHUD
@_exported import AFNetworking
@_exported import URLNavigator

/// flutter 发消息给Native 传递数据  方法名字
enum FlutterSendEventType: String {
    case appTestMethod
    case initSdk
    case sendData
}
public class SwiftYjHealthPlugin: NSObject {
    static let shareInstance = SwiftYjHealthPlugin()
    var eventChannel: YJKtvEventChannel?
}
extension SwiftYjHealthPlugin: FlutterPlugin {
  public static func register(with registrar: FlutterPluginRegistrar) {
    let channel = FlutterMethodChannel(name: "yj_health_plugin", binaryMessenger: registrar.messenger())
      let instance = SwiftYjHealthPlugin.shareInstance
    registrar.addMethodCallDelegate(instance, channel: channel)
    
      /// 监听通知事件//--------------------------------------监听通知事件
      let eventChannel = YJKtvEventChannel.init(messenger: registrar.messenger())
      instance.eventChannel = eventChannel
      
      /// 初始化蓝牙SDK 和 其他第三方
      SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.gradient)
      SVProgressHUD.setMaximumDismissTimeInterval(2.0)
      /// 采用同步任务模式
      KCTSingleBLEShell.sharedInstance.asyncEnable = false
      /// 打开SDK的打印
      KCTBluetoothLogManager.share.openLog = true

      
      // 路由
      YJURLNavigationMap.initializeMap()
      
  }

  public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
      
      if call.method == FlutterSendEventType.appTestMethod.rawValue {
          result("iOS " + UIDevice.current.systemVersion)
      } else if call.method == FlutterSendEventType.initSdk.rawValue {
//          result("初始化了。。。。")
          var dic = ["aa":"aaassssaaa"]
          SwiftYjHealthPlugin.shareInstance.sendToFlutter(dic.toJsonString())

          navigator.open(YJNavigationURLs.vc)
      } else if call.method == FlutterSendEventType.sendData.rawValue {
          guard let args = call.arguments as? [String: Any], let data = args["data"] as? [String: Any], let name = data["name"] as? String else { return }
          IPrint("==========start")
          IPrint(name)
          IPrint("==========end")
          if name == "scan_device" {
              let type = data["type"] as? Int
              if type == 0 {
                  YJDeviceManager.share.startScanWithFilter(filter: false)
              } else if type == 1 {
                  YJDeviceManager.share.startScanWithFilter(filter: true)
              }
          } else if name == "stop_device" {
              YJDeviceManager.share.stopScan()
          } else if name == "connect" {
              YJDeviceManager.share.connection()
          }
      } else {
          result(FlutterMethodNotImplemented)
      }
      
  }
    
    /// ios 发送给flutter 消息--------------------------------------------------------------------------------------------------------发
    func sendToFlutter(_ message: String?) {
        self.eventChannel?.sendMessageEventChannel(message)
    }
    
}



let navigator = Navigator()
struct YJNavigationURLs {
    static let vc = "yjapp://vc"
}
struct YJURLNavigationMap {
    
    static func initializeMap() {
        navigator.handle(YJNavigationURLs.vc) { _, _, context in
            let firstVC = FirstVC()
            YJNavigationController()?.pushViewController(firstVC, animated: true)
            return true
        }
    }
}


func YJNavigationController() -> UINavigationController? {
    if Thread.isMainThread == false {
        return nil
    }
    guard let visibleVC = UIApplication.visibleViewController else {
        return nil
    }
    return visibleVC.navigationController
}

       
// MARK: - UIApplication
public extension NSObject {

    @objc static var visibleViewController: UIViewController? {
        return NSObject.getVisibleViewController(from: UIApplication.shared.keyWindow?.rootViewController)
    }

    @objc static func getVisibleViewController(from vc: UIViewController?) -> UIViewController? {
        if let nav = vc as? UINavigationController {
            return getVisibleViewController(from: nav.visibleViewController)
        } else if let tab = vc as? UITabBarController {
            return getVisibleViewController(from: tab.selectedViewController)
        } else if let pvc = vc?.presentedViewController {
            return getVisibleViewController(from: pvc)
        }
        return vc
    }
}



class YJKtvEventChannel: NSObject {
    private var channel: FlutterEventChannel?
    private var eventSink: FlutterEventSink?

    init(messenger: FlutterBinaryMessenger) {
        channel = FlutterEventChannel(name: "yj_ktc_event", binaryMessenger: messenger, codec: FlutterStandardMethodCodec.sharedInstance())
        super.init()
        channel?.setStreamHandler(self)
    }

    func sendMessageEventChannel(_ message: String?) {
        if eventSink != nil {
            eventSink?(message)
        }
    }

}

extension YJKtvEventChannel: FlutterStreamHandler {
    func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? {
        eventSink = events
        return nil
    }
    
    func onCancel(withArguments arguments: Any?) -> FlutterError? {
        eventSink = nil
        return nil
    }
}

// MARK: 字典转字符串
extension Dictionary {
    
    func toJsonString() -> String? {
        guard let data = try? JSONSerialization.data(withJSONObject: self,
                                                     options: []) else {
            return nil
        }
        guard let str = String(data: data, encoding: .utf8) else {
            return nil
        }
        return str
     }
    
}
// MARK: 字符串转字典
extension String {
    
    func toDictionary() -> [String: Any]? {
        if let data = self.data(using: String.Encoding.utf8) {
            do {
                let opt = JSONSerialization.ReadingOptions.init(rawValue: 0)
                return try JSONSerialization.jsonObject(with: data, options: [opt]) as? [String: Any]
            } catch let error as NSError {
                print(error)
            }
        }
        return nil
    }
    func toArray() -> [[String: Any]]? {
        if let data = self.data(using: String.Encoding.utf8) {
            do {
                let opt = JSONSerialization.ReadingOptions.init(rawValue: 0)
                return try JSONSerialization.jsonObject(with: data, options: [opt]) as? [[String: Any]]
            } catch let error as NSError {
                print(error)
            }
        }
        return nil
    }
}



func IPrint<T>(_ message:T,file:String = #file,funcName:String = #function,lineNum:Int = #line){
    let file = (file as NSString).lastPathComponent;
    let now = Date.init()
    let log = KCTLogModel.init()
    log.modulName = "SDKDemo"
    log.time = now.timeIntervalSince1970
    log.fileName = file
    log.funcName = funcName
    log.lineNum = lineNum
    log.message = message
    
    let msgDes = NSString.init(string: "\(message)")
    let fileDes = NSString.init(string: "\(file)")
    let funcDes = NSString.init(string: "\(funcName)")
    let lineDes = NSString.init(string: "\(lineNum)")
    
    NSLog("[SDKDemo] [%@ %@][%@] %@", fileDes,funcDes,lineDes,msgDes)
    
}
